package com.crtf.kotlin.maven.lombok.java.dto

import lombok.AllArgsConstructor
import lombok.Builder
import lombok.Data
import lombok.NoArgsConstructor
import java.util.function.Function

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class ResultDTO<T>(
    var code: String? = null,
    var msg: String? = null,
    var data: T? = null,
) {


    companion object {
        infix fun <T> of(
            value: Result<T>
        ): ResultDTO<T> {
            return parse(value)
        }

        fun <T> parse(
            value: Result<T>,
            codeParse: Function<Result<T>, String?>? = Function { if (it.isSuccess) "200" else "500" },
            msgParse: Function<Result<T>, String?>? = Function { if (it.isSuccess) "成功" else "失败: ${value.exceptionOrNull()?.message}" },
        ): ResultDTO<T> {
            val code = codeParse?.apply(value)
            val msg = msgParse?.apply(value)
            return ResultDTO(code, msg, value.getOrNull())
        }

    }

}